package Login.servlet;

import Login.entity.User;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.Enumeration;

@WebServlet(name = "LoginServlet", urlPatterns = "/Login")
public class LoginServlet extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        // 获取user和password
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println(username+ "-" + password);

        // 检验
        if ("TheK".equals(username) && "123456".equals(password)) {
            // 登录成功 将用户状态 user 对象存入 session
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            request.getSession().setAttribute("user", user);
            // 发送自动登录的cookie
            String autoLogin = request.getParameter("username");
            if (autoLogin != null) {
                Cookie cookie = new Cookie("autologin", username + "-" + password);
                // 设置cookie过期时间为15min
                cookie.setMaxAge(15*60);
                cookie.setPath(request.getContextPath());
                HttpSession session = request.getSession();
                session.setAttribute("userName", username);
                response.addCookie(cookie);
            }
            // 跳转首页
            request.getRequestDispatcher("/index.jsp").forward(request,response);
            //response.sendRedirect(request.getContextPath()+"/index.jsp");
            } else {
            request.setAttribute("errerMsg", "用户名或密码错误");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        }
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        doGet(request, response);
    }
}
